package net.sf.rose.file.monitor;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.util.HashSet;
import java.util.Set;

import net.sf.rose.util.RoseRuntimeException;

/**
 * @description : 将文件变化情况保存至指定文件中
 * @author : fengjian
 * @since : 2021-07-03
 * @see FileMonitor
 */
public class FileMonitorReocrd extends FileMonitor {

    /**
     * 文件创建
     */
    @Override
    public void onFileCreate(File file) {
        this.record(file);
    }

    /**
     * 文件修改
     */
    @Override
    public void onFileChange(File file) {
        this.record(file);
    }

    private void record(File file) {
        try {
            // 获取该文件的缓冲输出流
            BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(path, true), "UTF-8"));
            // 写入信息
            bw.write(file.getAbsolutePath() + "\n");
            bw.flush();// 清空缓冲区
            bw.close();// 关闭输出流
        } catch (Exception e) {
            throw new RoseRuntimeException(e);
        }
    }

    private static File path = null;

    /**
     * recordFile - 监控目录
     * 
     * @param recordFile - 监控目录
     * @return 监控目录是否成功
     */
    public static boolean setRecordFile(File recordFile) {
        path = recordFile;
        if (!path.exists()) {
            try {
                path.createNewFile();
            } catch (Exception e) {
                e.printStackTrace();
                return false;
            }
        }
        return true;
    }

    /**
     * 读取保存的临时修改文件记录
     * 
     * @return 字符串
     * @throws RoseRuntimeException 文件流操作异常
     */
    public static Set<String> readData() {
        Set<String> list = new HashSet<>();
        try {
            BufferedReader in = null;
            in = new BufferedReader(new InputStreamReader(new FileInputStream(path), "utf-8"));
            String str;
            while ((str = in.readLine()) != null) {
                list.add(str);
            }
            in.close();
            // 清空文件
            BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(path), "UTF-8"));
            bw.write("");
            bw.flush();// 清空缓冲区
            bw.close();// 关闭输出流
        } catch (Exception e) {
            throw new RoseRuntimeException(e);
        }
        return list;
    }

}